import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:math' as math;
import '../models/acceptance_category.dart';
import '../models/acceptance_form.dart';
import '../services/acceptance_service.dart';

// 打印对话框
class PrintDialog extends StatefulWidget {
  const PrintDialog({super.key});

  @override
  State<PrintDialog> createState() => _PrintDialogState();
}

class _PrintDialogState extends State<PrintDialog> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _scaleAnimation;
  late Animation<double> _fadeAnimation;
  late Animation<double> _rotateAnimation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 800),
    );

    _scaleAnimation = Tween<double>(begin: 0.8, end: 1.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: const Interval(0.0, 0.6, curve: Curves.elasticOut),
      ),
    );

    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: const Interval(0.0, 0.6, curve: Curves.easeIn),
      ),
    );

    _rotateAnimation = Tween<double>(begin: -0.1, end: 0.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: const Interval(0.0, 0.6, curve: Curves.elasticOut),
      ),
    );

    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return Transform(
          transform: Matrix4.identity()
            ..scale(_scaleAnimation.value)
            ..rotateZ(_rotateAnimation.value),
          child: Opacity(
            opacity: _fadeAnimation.value,
            child: AlertDialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
              ),
              title: Row(
                children: [
                  Icon(
                    Icons.check_circle,
                    color: const Color(0xFF10B981),
                    size: 28,
                  ),
                  const SizedBox(width: 12),
                  const Text(
                    '提交成功',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Text(
                    '是否打印受理单？',
                    style: TextStyle(
                      fontSize: 16,
                      color: Color(0xFF64748B),
                    ),
                  ),
                  const SizedBox(height: 16),
                  Container(
                    padding: const EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      color: const Color(0xFFF8FAFC),
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(
                        color: const Color(0xFFE2E8F0),
                        width: 1,
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.print_rounded,
                          color: const Color(0xFF2563EB),
                          size: 24,
                        ),
                        const SizedBox(width: 8),
                        const Text(
                          '打印受理单',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Color(0xFF2563EB),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context, false),
                  child: const Text(
                    '否',
                    style: TextStyle(
                      color: Color(0xFF64748B),
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                ElevatedButton(
                  onPressed: () => Navigator.pop(context, true),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF2563EB),
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: const Text(
                    '是',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}

class AcceptanceFormScreen extends StatefulWidget {
  const AcceptanceFormScreen({super.key});

  @override
  State<AcceptanceFormScreen> createState() => _AcceptanceFormScreenState();
}

class _AcceptanceFormScreenState extends State<AcceptanceFormScreen> {
  final _formKey = GlobalKey<FormState>();
  final AcceptanceService _acceptanceService = AcceptanceService();
  
  // 表单数据
  final _form = AcceptanceForm(
    formNumber: '',
    acceptanceDate: DateTime.now(),
    applicantName: '',
    applicantPhone: '',
    applicantIdCard: '',
    respondentName: '',
    respondentPhone: '',
    respondentIdCard: '',
    disputeDescription: '',
    acceptorName: '',
    acceptorUnit: '',
    acceptorPhone: '',
    categoryId: 0,
    status: 1,
  );

  // 分类数据
  List<AcceptanceCategory> _parentCategories = [];
  List<AcceptanceCategory> _childCategories = [];
  AcceptanceCategory? _selectedParentCategory;
  AcceptanceCategory? _selectedChildCategory;
  bool _isEditable = false; // 添加表单编辑状态控制
  bool _isLoading = false; // 添加加载状态控制

  @override
  void initState() {
    super.initState();
    _loadCategories();
    _generateFormNumber();
  }

  // 加载分类数据
  Future<void> _loadCategories() async {
    try {
      final categories = await _acceptanceService.getCategories();
      setState(() {
        _parentCategories = categories.where((c) => c.level == 1).toList();
      });
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载分类失败: $e')),
      );
    }
  }

  // 生成受理单编号
  Future<void> _generateFormNumber() async {
    try {
      final formNumber = await _acceptanceService.generateFormNumber();
      setState(() {
        _form.formNumber = formNumber;
      });
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('生成受理单编号失败: $e')),
      );
    }
  }

  // 当选择父分类时
  void _onParentCategoryChanged(AcceptanceCategory? category) {
    setState(() {
      _selectedParentCategory = category;
      _selectedChildCategory = null;
      if (category != null) {
        _childCategories = _acceptanceService.categories
            .where((c) => c.parentId == category.id)
            .toList();
      } else {
        _childCategories = [];
      }
    });
  }

  // 重置表单
  void _resetForm() async {
    setState(() {
      _form.acceptanceDate = DateTime.now();
      _form.applicantName = '';
      _form.applicantPhone = '';
      _form.applicantIdCard = '';
      _form.respondentName = '';
      _form.respondentPhone = '';
      _form.respondentIdCard = '';
      _form.disputeDescription = '';
      _form.acceptorName = '';
      _form.acceptorUnit = '';
      _form.acceptorPhone = '';
      _form.categoryId = 0;
      _selectedParentCategory = null;
      _selectedChildCategory = null;
      _childCategories = [];
      _isEditable = true; // 重置表单时设置为可编辑状态
    });
    _formKey.currentState?.reset();
    await _generateFormNumber(); // 等待生成新的受理单编号
  }

  // 保存表单
  Future<void> _saveForm() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      
      if (_selectedChildCategory == null) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('请选择具体纠纷类型')),
        );
        return;
      }

      _form.categoryId = _selectedChildCategory!.id;
      
      try {
        await _acceptanceService.createAcceptanceForm(_form);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('保存成功')),
        );
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('保存失败: $e')),
        );
      }
    }
  }

  // 提交表单
  Future<void> _submitForm() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() => _isLoading = true);
    try {
      await _acceptanceService.createAcceptanceForm(_form);
      if (mounted) {
        setState(() => _isLoading = false);
        // 显示提交成功提示
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('受理单提交成功')),
        );
        
        // 显示打印提示对话框
        final shouldPrint = await showDialog<bool>(
          context: context,
          builder: (context) => const PrintDialog(),
        );

        if (shouldPrint == true) {
          // TODO: 实现打印功能
          // Navigator.push(
          //   context,
          //   MaterialPageRoute(
          //     builder: (context) => PrintAcceptanceFormScreen(form: _form),
          //   ),
          // );
        }
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('提交失败: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8FAFC),
      body: Column(
        children: [
          // 顶部操作栏
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.1),
                  blurRadius: 10,
                  offset: const Offset(0, 5),
                ),
              ],
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '受理单登记',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF1E293B),
                  ),
                ),
                Row(
                  children: [
                    // 新建登记按钮
                    ElevatedButton.icon(
                      onPressed: _resetForm,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF10B981),
                        foregroundColor: Colors.white,
                        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                      ),
                      icon: const Icon(Icons.add_circle, size: 18),
                      label: const Text('新建登记'),
                    ),
                    const SizedBox(width: 12),
                    // 提交按钮
                    ElevatedButton.icon(
                      onPressed: _isEditable ? _submitForm : null,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF2563EB),
                        foregroundColor: Colors.white,
                        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                      ),
                      icon: const Icon(Icons.check_circle, size: 18),
                      label: const Text('提交'),
                    ),
                  ],
                ),
              ],
            ),
          ),
          // 表单内容
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(24),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 基本信息
                    const Text('基本信息', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 16),
                    Row(
                      children: [
                        // 受理单编号
                        Expanded(
                          child: TextFormField(
                            decoration: InputDecoration(
                              labelText: '受理单编号',
                              border: const OutlineInputBorder(),
                              labelStyle: TextStyle(
                                color: _form.formNumber.isNotEmpty ? Colors.red : null,
                              ),
                            ),
                            style: TextStyle(
                              color: _form.formNumber.isNotEmpty ? Colors.red : null,
                              fontWeight: _form.formNumber.isNotEmpty ? FontWeight.bold : null,
                            ),
                            initialValue: _form.formNumber,
                            readOnly: true,
                          ),
                        ),
                        const SizedBox(width: 16),
                        // 受理日期
                        Expanded(
                          child: TextFormField(
                            decoration: const InputDecoration(
                              labelText: '受理日期',
                              border: OutlineInputBorder(),
                              suffixIcon: Icon(Icons.calendar_today),
                            ),
                            controller: TextEditingController(
                              text: DateFormat('yyyy-MM-dd').format(_form.acceptanceDate),
                            ),
                            readOnly: !_isEditable,
                            onTap: _isEditable ? () async {
                              final date = await showDatePicker(
                                context: context,
                                initialDate: _form.acceptanceDate,
                                firstDate: DateTime(2000),
                                lastDate: DateTime(2100),
                              );
                              if (date != null) {
                                setState(() {
                                  _form.acceptanceDate = date;
                                });
                              }
                            } : null,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    // 纠纷分类选择
                    Row(
                      children: [
                        // 纠纷大类
                        Expanded(
                          child: DropdownButtonFormField<AcceptanceCategory>(
                            decoration: const InputDecoration(
                              labelText: '纠纷大类',
                              border: OutlineInputBorder(),
                            ),
                            value: _selectedParentCategory,
                            items: _parentCategories.map((category) {
                              return DropdownMenuItem(
                                value: category,
                                child: Text(category.name),
                              );
                            }).toList(),
                            onChanged: _isEditable ? _onParentCategoryChanged : null,
                            validator: (value) {
                              if (value == null) return '请选择纠纷大类';
                              return null;
                            },
                          ),
                        ),
                        const SizedBox(width: 16),
                        // 具体纠纷类型
                        Expanded(
                          child: DropdownButtonFormField<AcceptanceCategory>(
                            decoration: const InputDecoration(
                              labelText: '具体纠纷类型',
                              border: OutlineInputBorder(),
                            ),
                            value: _selectedChildCategory,
                            items: _childCategories.map((category) {
                              return DropdownMenuItem(
                                value: category,
                                child: Text(category.name),
                              );
                            }).toList(),
                            onChanged: _isEditable ? (category) {
                              setState(() => _selectedChildCategory = category);
                            } : null,
                            validator: (value) {
                              if (value == null) return '请选择具体纠纷类型';
                              return null;
                            },
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 32),

                    // 申请人信息
                    const Text('申请人信息', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 16),
                    // 申请人信息 - 姓名和电话在同一行
                    Row(
                      children: [
                        Expanded(
                          child: TextFormField(
                            decoration: const InputDecoration(
                              labelText: '申请人姓名',
                              border: OutlineInputBorder(),
                            ),
                            enabled: _isEditable,
                            onChanged: (value) => _form.applicantName = value,
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return '请输入申请人姓名';
                              }
                              return null;
                            },
                          ),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: TextFormField(
                            decoration: const InputDecoration(
                              labelText: '申请人电话',
                              border: OutlineInputBorder(),
                            ),
                            enabled: _isEditable,
                            onChanged: (value) => _form.applicantPhone = value,
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return '请输入申请人电话';
                              }
                              return null;
                            },
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    TextFormField(
                      decoration: const InputDecoration(
                        labelText: '申请人身份证号',
                        border: OutlineInputBorder(),
                      ),
                      enabled: _isEditable,
                      onChanged: (value) => _form.applicantIdCard = value,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入申请人身份证号';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 32),

                    // 被申请人信息
                    const Text('被申请人信息', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 16),
                    // 被申请人信息 - 姓名和电话在同一行
                    Row(
                      children: [
                        Expanded(
                          child: TextFormField(
                            decoration: const InputDecoration(
                              labelText: '被申请人姓名',
                              border: OutlineInputBorder(),
                            ),
                            enabled: _isEditable,
                            onChanged: (value) => _form.respondentName = value,
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return '请输入被申请人姓名';
                              }
                              return null;
                            },
                          ),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: TextFormField(
                            decoration: const InputDecoration(
                              labelText: '被申请人电话',
                              border: OutlineInputBorder(),
                            ),
                            enabled: _isEditable,
                            onChanged: (value) => _form.respondentPhone = value,
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return '请输入被申请人电话';
                              }
                              return null;
                            },
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    TextFormField(
                      decoration: const InputDecoration(
                        labelText: '被申请人身份证号',
                        border: OutlineInputBorder(),
                      ),
                      enabled: _isEditable,
                      onChanged: (value) => _form.respondentIdCard = value,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入被申请人身份证号';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 16),
                    TextFormField(
                      decoration: const InputDecoration(
                        labelText: '纠纷描述',
                        border: OutlineInputBorder(),
                      ),
                      maxLines: 3,
                      enabled: _isEditable,
                      onChanged: (value) => _form.disputeDescription = value,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入纠纷描述';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 32),

                    // 受理人信息
                    const Text('受理人信息', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 16),
                    // 受理人信息 - 姓名和电话在同一行
                    Row(
                      children: [
                        Expanded(
                          child: TextFormField(
                            decoration: const InputDecoration(
                              labelText: '受理人姓名',
                              border: OutlineInputBorder(),
                            ),
                            enabled: _isEditable,
                            onChanged: (value) => _form.acceptorName = value,
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return '请输入受理人姓名';
                              }
                              return null;
                            },
                          ),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: TextFormField(
                            decoration: const InputDecoration(
                              labelText: '受理人电话',
                              border: OutlineInputBorder(),
                            ),
                            enabled: _isEditable,
                            onChanged: (value) => _form.acceptorPhone = value,
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return '请输入受理人电话';
                              }
                              return null;
                            },
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    TextFormField(
                      decoration: const InputDecoration(
                        labelText: '受理单位',
                        border: OutlineInputBorder(),
                      ),
                      enabled: _isEditable,
                      onChanged: (value) => _form.acceptorUnit = value,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入受理单位';
                        }
                        return null;
                      },
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
} 